import graphics, math, pygame, colors
from gameObject import GameObject
from explosions import Explosion

class Bullet( GameObject ):
    """
    GameObject created by Tanks when shooting.
    """
    SPEED = 150
    DAMAGE = 1.0
    
    def __init__(self, x, y, angle, team, game):
        """
        Creates and sets up the bullet based on *turret* coordinates x, y.
        """
        # First initiate GameObject since this is a new __init__.
        GameObject.__init__(self)
        ##########################
        # BULLET STATE VARIABLES #
        ##########################
         # Position the bullet at the end of the turret's cannon.
        self.x = x + (2 + 16) * math.cos(angle)
        self.y = y + (- 2 - 16) * math.sin(angle)
        self.angle = - angle 
        self.speed = Bullet.SPEED
        self.dt = 0.0
        self.team = team
        self.game = game
        #############################
        # BULLET GRAPHICS VARIABLES #
        #############################
        self.image = graphics.loadImage("sprites/"+self.team+"Bullet.png")
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)
        self.mask = pygame.mask.from_surface(self.image)

    def update(self, previousTime, currentTime):
        self.dt = currentTime - previousTime
        tanks = self.detectCollision([self.game.tanks]) 
        if len(tanks) == 0:
            self.x += math.cos(self.angle) * self.dt * self.speed
            self.y += math.sin(self.angle) * self.dt * self.speed
            self.rect.center = (self.x, self.y)
        else:
            self.game.bullets.remove(self)
            for t in tanks:
                t.hp -= Bullet.DAMAGE
        if self.boundaryConditions(self.x, self.y) == True:
            self.game.bullets.remove(self)
            self.game.explosions.add( Explosion(self.x, self.y, self.angle, currentTime, self.game, kind="bullet") )
    def clear(self):
        self.game.display.blit(self.game.background, self.rect, self.rect)

    def draw(self):
        self.game.display.blit(self.image, self.rect)
       
    def boundaryConditions(self, x, y):
        """
        Returns True if the bullet is hitting the edge of the screen and False 
        otherwise. 
        """
        display_x = graphics.Graphics.WIDTH 
        display_y = graphics.Graphics.HEIGHT
        if x >= display_x or y >= display_y or x < 0 or y < 0:
            return True
        else:
            return False

